/**
 * @author alonsocucei
 * @version 1.0
 */
package modulo1.util;

import java.util.InputMismatchException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Scanner;
import java.util.Stack;

public class MenuDisplay {
    private Locale currentLocale = Locale.getDefault();
    private ResourceBundle bundle = ResourceBundle.getBundle("modulo1.locales.MenuDisplayBundle", currentLocale);
    private Scanner scanner;
    private Stack<DVDMenu> menuStack;

    /**
     * Constructs a new <code>MenuDisplay</code> object with its root menu
     * @param menu the root menu to use
     */
    public MenuDisplay(DVDMenu menu) {
        scanner = new Scanner(System.in);
        menuStack = new Stack<>();
        menuStack.push(menu);
    }

    /**
     * Sets the locale for this <code>MenuDisplay</code> which is reflected when
     * invoking the method <code>display</code>.
     * @param locale the locale for this object
     */
    public void setLocale(Locale locale) {
        currentLocale = locale;
        bundle = ResourceBundle.getBundle("modulo1.locales.MenuDisplayBundle", currentLocale);
    }
    
    /**
     * Displays the root menu, and its submenus or actions.
     * This method iterates in a loop while the exit options is not selected.
     */
    public void display() {
        //scanner.useLocale();        
        int option = 0;
        do {
            System.out.println(bundle.getString("movieTitle"));
            System.out.println(menuStack.peek());
            System.out.println(bundle.getString("option"));
            
            try {
                option = scanner.nextInt();
                int itemsLength = menuStack.peek().getItemsLength();                

                if (option <= itemsLength && option > 0) {
                    Object item = menuStack.peek().getItems()[option - 1];
                    
                    if (item instanceof DVDMenu) {
                        menuStack.push((DVDMenu) item);
                    } else if (item instanceof Action) {
                        Action action = (Action) item;
                        action.doAction();
                    } else { //String
                        if (option == itemsLength) { //exit
                            option = -1;
                        } else if (!menuStack.peek().isRoot() && option == itemsLength - 1) { //back to previous menu
                            menuStack.pop();
                        }
                    }
                } else {
                    throw new InputMismatchException(bundle.getString("invalidOption"));
                }
            } catch (InputMismatchException e) {
                System.out.println(bundle.getString("invalidEntry"));
                scanner.next(); //skip invalid entry
            }
        } while (option != -1);
    }
}